package com.lushu.helpers.structure
{
	import com.lushu.data.interfaces.ITreeProvider;
	import com.lushu.typedArrays.ArrayList;
	
	import flash.events.EventDispatcher;
	
	public class TreeNode extends EventDispatcher
	{
		private var children_ : ArrayList;
		private var name_ : String
		private var data_ : ITreeProvider;
		private var dataIndex_ : int;
		private var isLeaf_ : Boolean;
		
		public function TreeNode(label : String)
		{
			name_ = label;
			children_ = new ArrayList(0, TreeNode);
			isLeaf_ = false;
		}
		
		public function getName() : String
		{
			return name_;
		}
		
		public function getChildByName(name : String) : TreeNode
		{
			var treeNode : TreeNode;
			var child : TreeNode;
			for(var i : int = 0; i < children_.size(); i++)
			{
				treeNode = children_.getItemAt(i) as  TreeNode;
				if(treeNode.getName() == name)
					return treeNode;
				else
				{
					child = treeNode.getChildByName(name);
					if(child != null)
						return child;
				}
			}
			return null;
		}
		
		public function addChild(node : TreeNode) : void
		{
			children_.addItem(node);
		}
		
		public function setData(image : ITreeProvider) : void
		{
			data_ = image;
			isLeaf_ = true;
		}
		
		public function getData() : ITreeProvider
		{
			return data_;
		}
		
		public function write() : XML
		{
			var xml :XML;
			if(!isLeaf_)
			{
				if(name_ == "root")
					xml = new XML("<root></root>");
				else if(data_ != null)
					xml = new XML('<rep label="'+name_+'" data="'+data_.getName()+'"></rep>');				
				else
					xml = new XML('<rep label="'+name_+'" data="'+name_+'"></rep>');
			}
			else
			{
				xml = new XML('<leaf label="'+name_+'" data="'+data_.getName()+'"></leaf>');
			}
			var subXML : XML;
			if(!isLeaf_)
			{
				for(var i : int = 0; i < children_.size(); i++)
				{
					subXML = (children_.getItemAt(i) as TreeNode).write();
					xml.appendChild(subXML);
				}
			}
			return xml;
		}
	}
}